package edu.gd.servlet;

import com.google.gson.Gson;
import edu.gd.dao.UserDao;
import edu.gd.entity.BaseResponse;
import edu.gd.entity.User;
import edu.gd.mvndemo.Insert;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user/reset/")
public class UserResetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String question=req.getParameter("question");
        String answer=req.getParameter("answer");
        User user= UserDao.getUserByID(username);
        BaseResponse baseResponse=new BaseResponse();
        if(user.getQuestion().equals(question)&&user.getAnswer().equals(answer)) {
            Insert.update(username, password);
            baseResponse.setCode(200);
            baseResponse.setMsg("成功");
        }
        else{
            baseResponse.setCode(500);
            baseResponse.setMsg("失败");
        }
        resp.setContentType("application/json;character=utf-8");
        Gson gson=new Gson();
        String json=gson.toJson(baseResponse);
        PrintWriter out=resp.getWriter();
        out.write(json);
        out.flush();
    }
}
